﻿using MessageServer.Update;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Data.SqlClient;
using AutoUpdateTools.Models;
using Rebex.IO.Compression;
using System.Diagnostics;
using AutoUpdateTools.Update;

namespace AutoUpdateTools
{
    /// <summary>
    /// 更新线程
    /// </summary>
    public class UpdateThread
    {
        
        public void Update(List<PackageUpdateModel> lstUpdateModel,List<PackageInfoEntity> lstAllPackInfo)
        {
            List<PackageAllInfo> lstPackage = new List<PackageAllInfo>();

            foreach (var item in lstUpdateModel)
            {
                var packageInfo = lstAllPackInfo.FirstOrDefault(n => n.PackageId == item.PackageId);
                if (packageInfo != null)
                {
                    lstPackage.Add(new PackageAllInfo
                    {
                        PackageId = item.PackageId,
                        LocalFilePath = item.LocalFilePath,
                        CheckVersionFile = packageInfo.CheckVersionFile,
                        PackageTypeString = packageInfo.PackageTypeString,
                    });
                }
            }

            while(true)
            {
                foreach (var item in lstPackage)
                {
                    IUpdateInterface updateService = null;
                    if(item.PackageTypeString == PackageType.web.ToString())
                    {
                        updateService = new WebUpdateClass(item);
                    }
                    else if(item.PackageTypeString == PackageType.exe.ToString())
                    {
                        updateService = new ExeUpdateClass(item);
                    }
                    else if (item.PackageTypeString == PackageType.database.ToString())
                    {
                        updateService = new DBUpdateClass(item);
                    }
                    else
                    {
                        updateService = null;
                    }
                    if (updateService == null)
                    {
                        continue;
                    } 
                    string version = updateService.GetVersion();  
                    if (string.IsNullOrEmpty(version) == false)
                    {
                        string updatePackageUrl = System.Configuration.ConfigurationManager.AppSettings["AutoUpdateUrl"] + "/api/PackageFile";
                        var entity = GetUpdatePackage(version, item.PackageId);

                        if (entity != null)
                        {
                            string localFilePath = downloadFile(entity.SavePath);
                            //如果下载的更新文件不存在,则执行下一个更新
                            if (!System.IO.File.Exists(localFilePath))
                            {
                                continue;
                            }
                            if (updateService.ExecBak(localFilePath, entity) == true)
                            {
                                if(!updateService.ExecUpdate())
                                {
                                    updateService.ExecRollBack();
                                } 
                            }
                        }
                    }
                }
                System.Threading.Thread.Sleep(10*60*1000); //10分钟检测一次
            }
           
        }
        /// <summary>
        /// 获取所有的包信息
        /// </summary>
        /// <returns></returns>
        public List<PackageInfoEntity> GetAllPackageInfo()
        {
            string webpath = System.Configuration.ConfigurationManager.AppSettings["AutoUpdateUrl"] + "/api/PackageInfo?pageIndex=0&pageSize=0";
            WebRequest request = WebRequest.Create(webpath);
            var response = request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            string content = reader.ReadToEnd();
            reader.Close();
            var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<PackageInfoList>(content);
            return obj.data;
        }
        private PackageSetupInfoEntity GetUpdatePackage(string version, int packageId)
        {
            string webpath = string.Format(System.Configuration.ConfigurationManager.AppSettings["AutoUpdateUrl"] + "/api/PackageFile?version={0}&packageId={1}", version, packageId);
            WebRequest request = WebRequest.Create(webpath);
            var response = request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            string content = reader.ReadToEnd();
            reader.Close();
            var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<PackageSetupInfoEntity>(content);
            return obj;
        }

        /// <summary>
        /// 获取下载的更新包
        /// </summary>
        /// <param name="savepath"></param>
        /// <returns></returns>
        private string downloadFile(string savepath)
        {
            string downloadUrl = System.Configuration.ConfigurationManager.AppSettings["AutoUpdateUrl"] + savepath;
            string PackageName = Path.GetFileName(downloadUrl);
            string localFilePath = string.Format(AppDomain.CurrentDomain.BaseDirectory, "temp", PackageName);
            if (System.IO.File.Exists(localFilePath) == true)
            {
                System.IO.File.Delete(localFilePath);
            }
            if (System.IO.Directory.Exists(Path.GetDirectoryName(localFilePath)) == false)
            {
                System.IO.Directory.CreateDirectory(Path.GetDirectoryName(localFilePath));
            }
            WebClient client = new WebClient();
            client.DownloadFile(downloadUrl, localFilePath);
            return localFilePath;
        }

        
             

    }
    public class PackageInfoList
    {
        public string code { get; set; }
        public string msg { get; set; }
        public int count { get; set; }

        public List<PackageInfoEntity> data { get; set; }

    }

    /// <summary>
    /// 更新文件类型
    /// </summary>
    public enum PackageType
    {
        /// <summary>
        /// WEB更新包
        /// </summary>
        web = 0,
        /// <summary>
        /// 更新数据库
        /// </summary>
        database = 1,
        /// <summary>
        /// 更新的可执行文件
        /// </summary>
        exe = 2,

    }
}
